﻿using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Windows;

namespace AuthorizedNavigation.Client.Services
{
    public static class AuthorizationHelperClasses
    {

        public static DependencyProperty GetDependencyProperty(object target, string propertyName)
        {
            string dependencyPropertyName = propertyName + "Property";

            FieldInfo field = target.GetType().GetField(
                dependencyPropertyName,
                BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);

            if ((field == null) || (field.FieldType != typeof(DependencyProperty)))
            {
                throw new InvalidOperationException(string.Format(
                    CultureInfo.CurrentCulture,
                    "There is no dependency property with the name '{0}' on the target of type '{1}' to bind to.",
                    dependencyPropertyName,
                    target.GetType()));
            }

            return (DependencyProperty)field.GetValue(null);
        }


        public static bool SetPropertyValueOnTarget(DependencyObject target, string propertyName)
        {

            var prop = GetDependencyProperty(target, propertyName);

            if (target.GetValue(prop) == null || target.GetValue(prop).GetType() == typeof(string))
            {
                target.SetValue(prop, String.Empty);
                return true;
            }

            if (target.GetValue(prop).GetType() == typeof(bool))
            {
                target.SetValue(prop, false);
                return true;
            }

            if (target.GetValue(prop).GetType() == typeof(Visibility))
            {
                target.SetValue(prop, Visibility.Collapsed);
                return true;
            }

            return false;

        }



    }

    public class StringArrayConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return (sourceType == typeof(string));
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            string valueString = value as string;
            return string.IsNullOrEmpty(valueString) ?
                new string[0] :
                valueString.Split(',').Select(s => s.Trim()).ToArray();
        }
    }
}
